import fetch from 'dva/fetch';
import { notification, Modal } from 'antd';
import router from 'umi/router';
import { connect } from 'dva';
import hash from 'hash.js';
import { isAntdPro, getToken, clearTokenCookie,isJsonString } from './utils';
import { SetHeads, checkStatus, cachedSave, awaitDemo, codeMessage, sleep } from './CommonRequestOption'
import showErrorMsg from '../utils/error';
const SERVICE_TYPE = APP_TYPE; //process.env.SERVICE_TYPE;


/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
// @connect(({ global }) => ({
//   global,
// }))
export default function request(
  url,
  options = {
    expirys: isAntdPro(),
  }
) {
  /**
   * Produce fingerprints based on url and parameters
   * Maybe url has the same parameters
   */

  if (window.authorization && getToken() != window.authorization) {
    let secondsToGo = 5;
    const modal = Modal.success({
      title: '系统提示',
      content: `检测到已重新登录，页面将刷新 ${secondsToGo} s后将自动刷新`,
      onOk: () => {
        location.reload();
      },
    });
    setInterval(() => {
      secondsToGo -= 1;
      modal.update({
        content: `检测到已重新登录，页面将刷新 ${secondsToGo} s后将自动刷新.`,
      });
    }, 1000);
    setTimeout(() => {
      location.reload();
    }, secondsToGo * 1000);
    return false;
  }
  if (url.indexOf('WXAuth/GoToWeixin') <= -1) {
    url = DOMAIN + url;
  }
  const fingerprint = url + (options.body ? JSON.stringify(options.body) : '');
  const hashcode = hash
    .sha256()
    .update(fingerprint)
    .digest('hex');

  const defaultOptions = {
    credentials: 'omit',
  };
  options = SetHeads(options);
  const newOptions = { ...defaultOptions, ...options };
  if (
    newOptions.method === 'POST' ||
    newOptions.method === 'PUT' ||
    newOptions.method === 'DELETE'
  ) {
    if (!(newOptions.body instanceof FormData)) {
      newOptions.headers = {
        Accept: 'application/json',
        'Content-Type': 'application/json; charset=utf-8',
        //"Cache-Control": "no-cache",
        ...newOptions.headers,
      };
      if(newOptions.headers['Content-Type'] !=='application/x-www-form-urlencoded'||newOptions.headers['credentials']!=='omit'){
        newOptions.body = typeof newOptions.body === 'string'? newOptions.body:JSON.stringify(newOptions.body);
      }
      //newOptions.body = JSON.stringify(newOptions.body);
    } else {
      // newOptions.body is FormData
      newOptions.headers = {
        Accept: 'application/json',
        //"Cache-Control":" no-cache",
        ...newOptions.headers,
      };
    }
  }

  const expirys = options.expirys || 1;
  // options.expirys !== false, return the cache,
  if (options.expirys !== false) {
    const cached = sessionStorage.getItem(hashcode);
    const whenCached = sessionStorage.getItem(`${hashcode}:timestamp`);
    if (cached !== null && whenCached !== null) {
      const age = (Date.now() - whenCached) / 1000;
      if (age < expirys) {
        const response = new Response(new Blob([cached]));
        return response.json();
      }
      sessionStorage.removeItem(hashcode);
      sessionStorage.removeItem(`${hashcode}:timestamp`);
    }
  }
  url = url.indexOf('?') > -1 ? `${url}&rend=${Math.random()}` : `${url}?rend=${Math.random()}`;
  return fetch(url, newOptions)
    .then(checkStatus)
    .then(response => cachedSave(response, hashcode))
    .then(response => {
      // DELETE and 204 do not return data by default
      // using .json will report an error.
      response
        .clone()
        .text()
        .then(function (res) {
          //全局抛出接口错误 错误信息对应errorjs文件
          if (!res) return;
          res = JSON.parse(res);
          if (res.Code == 30007 || res.Code == 30006 || res.Code == 30009 || res.Code == 30012) {
            location.href = res.Data;
          } else if (res.Code == 30008) {
            let secondsToGo = 5;
            const modal = Modal.success({
              title: '系统提示',
              content: `店铺未任何功能授权 ${secondsToGo} s后将自动跳转商家中心`,
              onOk: () => {
                location.href = res.Data;
              },
            });
            setInterval(() => {
              secondsToGo -= 1;
              modal.update({
                content: `店铺未任何功能授权 ${secondsToGo} s后将自动跳转商家中心.`,
              });
            }, 1000);
            setTimeout(() => {
              location.href = res.Data;
            }, secondsToGo * 1000);
            return false;
          }
          let codes = [];
          if (newOptions.body) {             
            if(newOptions.headers['Content-Type'] ==='application/x-www-form-urlencoded'||newOptions.headers['credentials']==='omit'){
                if (newOptions.body) codes =  [];
              }else{
                if(JSON.stringify(newOptions.body)==='{}'){
                  codes = [];
                }else{
                    if(isJsonString(newOptions.body)) {
                        if (JSON.parse(newOptions.body).codes) codes = JSON.parse(newOptions.body).codes || [];
                    } else {
                        codes = [];
                    }                  
                }                
              }            
          }
          if (codes.indexOf(res.code) < 0) {
            // let isStop=window.g_app._store.getState().global.isStop;
            // if (res.Code != 0) showErrorMsg(res, codes);
            // if(!isStop){
            //   window.g_app._store.dispatch({
            //     type:'global/changeIsStop',
            //     payload:true
            //   })
            // }
          }
        });
      if (newOptions.method === 'DELETE' || response.status === 204) {
        return response.text();
      }
      // if (SERVICE_TYPE && SERVICE_TYPE != 'pro') {
      //   return response.json();
      // } else {
      //   return awaitDemo(response.json(), 1000);
      // }
      return response.json();
    })
    .catch(e => {
      const status = e.name;

      if (status === 401) {
        // @HACK
        /* eslint-disable no-underscore-dangle */
        window.g_app._store.dispatch({
          type: 'login/logout',
        });
        return;
      }
      // environment should not be used
      if (status === 403) {
        router.push(`/${100000000001}/exception/403`);
        return;
      }
      if (status <= 504 || status >= 500) {

        router.push(`/${100000000001}/exception/500`);
        return;
      }
      if (status >= 404 && status < 422) {
        router.push(`/${100000000001}/exception/404`);
      }
    });
}
